<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { useFetch } from '@/home/hooks/fetch';
import { useAsyncData } from '@/home/hooks/async-data';

const { $fetch } = useFetch();
const isShow = ref(true);
const isHover = ref(false);
const currentIndex = ref(0);

let timer: ReturnType<typeof setInterval> | null = null;

const { data: noticeList } = useAsyncData<Record<string, any>[]>('header:noticebar', () => $fetch('/popNotice/getSelectList', { method: 'post' }));

const startNoticeLoop = () => {
  timer = setInterval(() => {
    if (!isHover.value) {
      currentIndex.value = (currentIndex.value + 1) % noticeList.value.length;
    }
  }, 5000);
};

const pauseNoticeLoop = () => {
  isHover.value = true;
};

const resumeNoticeLoop = () => {
  isHover.value = false;
};

const close = () => {
  isShow.value = false;

  if (timer) {
    clearInterval(timer);
  }
};

onMounted(() => {
  if (noticeList.value?.length > 1) {
    startNoticeLoop();
  }
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<template>
  <div class="bg-#fff p-8" v-if="isShow && noticeList?.length">
    <div class="h-32 flex-y-center justify-between rounded-6 bg-#3d7cfa px-6">
      <div class="w-50 flex-shrink-0"></div>

      <Transition name="notice-slide" mode="out-in" @mouseenter="pauseNoticeLoop" @mouseleave="resumeNoticeLoop">
        <ul :key="currentIndex" class="mx-100 flex-grow overflow-hidden">
          <template v-for="(notice, index) in noticeList" :key="notice.id">
            <li class="flex-y-center cursor-pointer justify-center gap-8 truncate" v-show="currentIndex === index">
              <div class="i-icons:notice size-20 flex-shrink-0 text-#fff"></div>
              <a class="truncate text-14 text-#fff font-400 leading-20" :href="notice.jumpLink" :title="notice.content" target="_blank">{{ notice.content }}</a>
            </li>
          </template>
        </ul>
      </Transition>

      <button
        type="button"
        class="flex-shrink-0 border-1 border-#fff rounded-4 bg-transparent px-12 py-2 text-12 text-#fff leading-16"
        @click="close()"
      >
        {{ $t('home.component.noticeBar.close') }}
      </button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.notice-slide-enter-active,
.notice-slide-leave-active {
  transition: all 0.5s linear;
}

.notice-slide-enter-from {
  transform: translateY(100%);
}

.notice-slide-enter-to {
  transform: translateY(0);
}

.notice-slide-leave-from {
  transform: translateY(0);
}

.notice-slide-leave-to {
  transform: translateY(-100%);
}
</style>
